package com.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tea.Model.Category;
import com.tea.Model.Goods;
import com.tea.Model.dto.CategoryBatchSortDTO;
import com.tea.mapper.GoodsMapper;
import com.tea.service.CategoryService;
import com.tea.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private GoodsMapper goodsMapper;

    // 分类列表（按排序字段排序）
    @GetMapping("/list")
    public Result<List<Category>> list() {
        List<Category> list = categoryService.listOrderBySort();
        return Result.success(list);
    }

    // 新增分类
    @PostMapping("/add")
    public Result<String> add(@RequestBody Category category) {
        category.setCategoryId(System.currentTimeMillis());
        // 如果没有设置排序值，设置为最大值+1
        if (category.getSortOrder() == null) {
            List<Category> allCategories = categoryService.list();
            int maxSort = allCategories.stream()
                    .mapToInt(c -> c.getSortOrder() != null ? c.getSortOrder() : 0)
                    .max()
                    .orElse(0);
            category.setSortOrder(maxSort + 1);
        }
        boolean success = categoryService.save(category);
        return success ? Result.success("添加成功") : Result.error("添加失败");
    }

    // 修改分类
    @PutMapping("/update")
    public Result<String> update(@RequestBody Category category) {
        if (category.getCategoryId() == null) {
            return Result.error("分类ID不能为空");
        }
        boolean success = categoryService.updateById(category);
        return success ? Result.success("修改成功") : Result.error("修改失败");
    }

    // 分类详情
    @GetMapping("/detail/{id}")
    public Result<Category> detail(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        return Result.success(category);
    }
    //删除
    @DeleteMapping("/{categoryId}")
    public Result<?> delete(@PathVariable Long categoryId) {
        Category category = categoryService.getById(categoryId);
        if (category == null) {
            return Result.error("分类不存在");
        }
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("category_id", categoryId);
        List<Goods> goods = goodsMapper.selectList(goodsQueryWrapper);
        if (goods == null || goods.isEmpty()) {
            boolean delResult = categoryService.removeById(categoryId);
            if (delResult) {
                return Result.success("删除成功");
            }
        }
        return Result.error("该分类存在商品，不可删除");
    }

    /**
     * 批量更新分类排序
     */
    @PutMapping("/batchSort")
    public Result<String> batchUpdateSort(@RequestBody @Valid CategoryBatchSortDTO batchSortDTO) {
        return categoryService.batchUpdateSort(batchSortDTO);
    }

    /**
     * 单个分类排序更新
     */
    @PutMapping("/sort/{categoryId}")
    public Result<String> updateSort(@PathVariable Long categoryId, @RequestParam Integer sortOrder) {
        return categoryService.updateSort(categoryId, sortOrder);
    }
}
